import sys
sys.path.append('/d:/CodeWork/Python/hello')
from jenkins_job import JenkinsJob
from config import JENKINS_URL, USERNAME, API_TOKEN

def compare_views(jenkins_job, view1, view2):
    view1_jobs = jenkins_job.get_jobs(view1['url'])
    view2_jobs = jenkins_job.get_jobs(view2['url'])

    if not view1_jobs or not view2_jobs:
        print("无法获取视图中的作业信息")
        return

    view1_server_names = {}
    view2_server_names = {}

    # 获取视图1中的Server Name信息
    for job in view1_jobs:
        job_name = job['name']
        server_name = jenkins_job.get_server_name(job_name)
        view1_server_names[job_name] = server_name

    # 获取视图2中的Server Name信息
    for job in view2_jobs:
        job_name = job['name']
        server_name = jenkins_job.get_server_name(job_name)
        view2_server_names[job_name] = server_name

    # 统计Server Name信息
    common_server_name_count = 0
    unique_server_name_count_view1 = 0
    unique_server_name_count_view2 = 0

    common_server_name_jobs = []
    unique_server_name_jobs_view1 = []
    unique_server_name_jobs_view2 = []

    for job_name, server_name in view1_server_names.items():
        if server_name in view2_server_names.values():
            common_server_name_count += 1
            common_server_name_jobs.append(job_name)
        else:
            unique_server_name_count_view1 += 1
            unique_server_name_jobs_view1.append(job_name)

    for job_name, server_name in view2_server_names.items():
        if server_name not in view1_server_names.values():
            unique_server_name_count_view2 += 1
            unique_server_name_jobs_view2.append(job_name)

    print(f"'{view1['name']}' ,'{view2['name']}'均已存在的job数量: {common_server_name_count}")
    print(f"具体job名称: {common_server_name_jobs}")
    print(f"仅在view '{view1['name']}' 中存在的job数量: {unique_server_name_count_view1}")
    print(f"具体job名称: {unique_server_name_jobs_view1}")
    print(f"仅在view '{view2['name']}' 中存在的job数量: {unique_server_name_count_view2}")
    print(f"具体job名称: {unique_server_name_jobs_view2}")

def main():
    jenkins_job = JenkinsJob(JENKINS_URL, USERNAME, API_TOKEN)
    
    print("选择第一个视图")
    view1 = jenkins_job.select_view()
    if not view1:
        print("未选择视图，程序退出")
        return
    
    print("选择第二个视图")
    view2 = jenkins_job.select_view()
    if not view2:
        print("未选择视图，程序退出")
        return

    compare_views(jenkins_job, view1, view2)

if __name__ == "__main__":
    main()